package com.tmall.testgen.client.genfile.genxml;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tmall.testgen.client.ClientDataCenter;
import com.tmall.testgen.client.config.ConfigUtil;
import com.tmall.testgen.client.config.TargetProjectConfig;
import com.tmall.testgen.client.genfile.genjava.bo.MethodSnap;
import com.tmall.testgen.common.bo.interact.back.InterceptInfo;
import com.tmall.testgen.common.util.StringUtil;
/**
 * @author haojia
 * @date 2014-07-04
 */
public class GenXMLCenter {

	public static void writeParamAndResultToXML(String fileFullPath,List<InterceptInfo> toBeGenInfos) throws Exception{
		Map<String,MethodSnap> result=new HashMap<String,MethodSnap>();
		 Map<String,MethodSnap> mockResult=new HashMap<String,MethodSnap>();
		
		Map<String,Integer> count=new HashMap<String,Integer>();
		
		for(InterceptInfo info: toBeGenInfos){
		    if(info.getType()==InterceptInfo.TYPE_INTERCEPT)
		        handleIntercept(result,count,info);
		    else
		        handleMock(mockResult,info);
		}
		
		
		ClassInfoForXML cif=new ClassInfoForXML();
		cif.setDbInfo(ClientDataCenter.getInstance().getDbInfo());
		cif.setSnaps(result);
		cif.setMockSnaps(mockResult);
		cif.setSql(ClientDataCenter.getInstance().getSqlSnap());
		cif.setRefProjectClassPathes(ConfigUtil.getRefProjectOutputs(TargetProjectConfig.getInstance().getTargetProjectName(), false));
		cif.setTargetConfigPath(TargetProjectConfig.getInstance().getTargetProjectConfigPath());
		cif.setMockDes(ClientDataCenter.getInstance().getMockDes());
		XMLFileOperator.toXML(fileFullPath, cif);
		
	}
	
	private static void handleIntercept(Map<String,MethodSnap> result,Map<String,Integer> count,InterceptInfo info){
	    String showName=info.getBeanName()==null?StringUtil.firstCharToLower(info.getClassSimpleName()):info.getBeanName();
        
        String key=showName+"_"+info.getMethodName();
        if(count.get(key)==null){
            count.put(key, 0);
        }
    
        String methodName=showName+"_"+info.getMethodName();
        if(count.get(key)>0)
            methodName=showName+"_"+info.getMethodName()+"_"+count.get(key);
        
        count.put(key, count.get(key)+1);
        
        
        MethodSnap snap=new MethodSnap();
        snap.setMethodName(methodName);
        snap.setParams(info.getParams());
        snap.setResult(info.getResult());
        result.put(methodName, snap);
        
	}
	private static void handleMock(Map<String,MethodSnap> mockResult,InterceptInfo info){
            MethodSnap snap=new MethodSnap();
            snap.setMethodName(info.getMethodName());
            snap.setParams(info.getParams());
            snap.setResult(info.getResult());
            mockResult.put(info.getClassName()+"."+info.getMethodName()+info.getMethodParamContent(), snap);
            
	}
}
